<template>
  <div>
    <!-- 头部表单信息 -->
    <el-card class="box-card">
      <el-form :inline="true" :model="workOrderInfo">
        <el-form-item label="工单编号:">
          <el-input v-model="workOrderInfo.taskCode" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="工单状态:">
          <el-select v-model="workOrderInfo.status" placeholder="请选择">
            <el-option v-for="item in stateList" :key="item.statusId" :label="item.statusName" :value="item.statusId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间main区域 -->
    <el-card class="box-card">
      <!-- 按钮区 -->
      <div>
        <el-button type="warning" icon="el-icon-circle-plus-outline" @click="showCreateOrder">新建</el-button>
        <el-button type="warning" plain @click="showalertDIalog">工单配置</el-button>
      </div>
      <!-- 工单表格区 -->
      <div>
        <el-table
          v-loading="loading"
          :data="orderLists"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="180"
          />
          <el-table-column
            prop="taskCode"
            label="工单编号"
            width="180"
          />
          <el-table-column
            prop="innerCode"
            label="设备编号"
          />
          <el-table-column
            prop="taskType.typeName"
            label="工单类型"
          />
          <el-table-column
            prop="createType"
            label="工单方式"
          >
            <template v-slot="scope">
              <span>{{ typeMap[scope.row.createType] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="taskStatusTypeEntity.statusName"
            label="工单状态"
          />
          <el-table-column
            prop="userName"
            label="运营人员"
          />
          <el-table-column
            prop="createTime"
            label="创建日期"
          />
          <el-table-column
            label="操作"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleClick(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <el-pagination
        layout="slot"
        :total="totalPage"
      >
        <span class="left">共{{ totalCount }}条记录 第{{ pageIndex }}/{{ totalPage }}页</span>
        <div class="btns">
          <button class="btn" :disabled="pageIndex===1" @click="dowmFn(-1)"><span>上一页</span></button>
          <button class="btn" @click="dowmFn(1)"><span>下一页</span></button>
        </div>
      </el-pagination>
      <!-- 查看详情dialog -->
      <el-dialog
        title="工单详情"
        :visible="detailsVisible"
        width="40%"
        @close="closedetailsVisible"
      >
        <div class="titleImg">
          <div class="titleImgLeft">
            <img :src="titleImg" alt="">
            <span>{{ detailList.taskStatusTypeEntity }}</span>
          </div>
          <div class="titleImgRight"><img :src="titleImg1" alt=""></div>
        </div>
        <el-form
          :model="detailList"
          label-width="100px"
          :inline="true"
        >

          <el-form-item label="设备编号:">
            <el-input v-model="detailList.innerCode" readonly style="width:100%;" />
          </el-form-item>
          <el-form-item label="创建日期:">
            <el-input v-model="detailList.createTime" readonly style="width:100%;" />
          </el-form-item>

          <el-form-item label="运营人员:">
            <el-input v-model="detailList.userName" readonly style="width:100%;" />
          </el-form-item>
          <el-form-item label="工单类型:">
            <el-input v-model="detailList.taskType" readonly style="width:100%;" />
          </el-form-item>
          <el-form-item label="工单方式:">
            <el-input v-model="typeMap[detailList.createType]" readonly style="width:100%;" />
          </el-form-item>
          <el-form-item label="补货数量:">
            <span class="detailBtn" style="font-size: 14px;width: 100%;" @click="repDetail">补货详情</span>
          </el-form-item>
          <el-form-item label="备注:">
            <el-input v-model="detailList.desc" readonly style="width:100%;" />
          </el-form-item>
          <el-form-item v-if="detailList.taskStatusTypeEntity === '取消'" label="取消原因:">
            <el-input v-model="detailList.desc" readonly style="width:100%;" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="display: flex; justify-content: center; align-items: center">
          <el-button type="primary" @click="showDialog">{{ detailList.taskStatusTypeEntity === '取消'? '重新创建' : '取消工单' }}</el-button>
        </span>
      </el-dialog>
      <!-- 补货详情dialog -->
      <el-dialog
        title="补货详情"
        width="40%"
        :visible="repDialog"
        @close="closeRepDialog"
      >
        <el-table
          :data="repList"
          style="width: 100%"
          max-height="400px"
          highlight-current-row
        >
          <el-table-column
            prop="channelCode"
            label="货道编号"
            width="120"
          />
          <el-table-column
            prop="skuName"
            label="商品"
            width="250"
          />
          <el-table-column
            prop="expectCapacity"
            label="补货数量"
            width="200"
          /></el-table>
      </el-dialog>
      <!-- 重新创建dialog -->
      <el-dialog
        title="新增工单"
        :visible="againDialog"
        width="30%"
        @close="closeAgainDialog"
      >
        <el-form ref="creatFormRef" :model="creatForm" label-width="120px" :rules="creatFormRules">
          <el-form-item label="设备编号:" prop="innerCode">
            <el-input v-model="creatForm.innerCode" maxlength="10" show-word-limit @change="innerCodeBlur" />
          </el-form-item>
          <el-form-item label="工单类型:" prop="productType">
            <el-select v-model="creatForm.productType" placeholder="请选择">
              <el-option label="补货工单" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="补货数量">
            <el-button type="text" size="small" icon="el-icon-document" @click="openGoodsDialog">补货清单</el-button>
          </el-form-item>
          <el-form-item label="运营人员:" prop="assignorId">
            <el-select v-model="creatForm.assignorId">
              <el-option
                v-for="(item,index) in innerList"
                :key="index"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注:" prop="desc">
            <el-input v-model="creatForm.desc" type="textarea" maxlength="40" show-word-limit placeholder="请输入备注(不超过40字)" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeAgainDialog">取 消</el-button>
          <el-button type="primary" @click="submitCreate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 预警值dialog -->
      <el-dialog
        title="工单配置"
        :visible="alertDialog"
        width="30%"
        @close="alertDialog = false"
      >
        <el-form :model="orderAlert">
          <el-form-item label="补货警戒线:">
            <el-input-number v-model="orderAlert.alertValue" controls-position="right" :min="10" :max="100" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="alertDialog = false">取 消</el-button>
          <el-button type="primary" @click="alertDialog = false">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 商品清单dialog -->
      <el-dialog
        title="补货详情"
        :visible="goodsDialog"
        width="33%"
        @close="goodsDialog = false"
      >
        <el-table :data="channelList" style="width: 100%" max-height="400">
          <el-table-column property="channelCode" label="货道编号" />
          <el-table-column property="sku.skuName" label="商品名称" />
          <el-table-column property="currentCapacity" label="当前数量" />
          <el-table-column property="render" label="还可添加" />
          <el-table-column label="补满数量" width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.sku.brandName === '-'">{{ scope.row.max }}</span>
              <el-input-number
                v-else-if="scope.row.max === 0"
                v-model="scope.row.max"
                controls-position="right"
                :min="0"
                :max="0"
              />
              <el-input-number
                v-else
                :key="tablekey"
                v-model="scope.row.addNum"
                controls-position="right"
                :min="0"
                :max="scope.row.max"
                @change="handleChange(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="goodsDialog = false">取 消</el-button>
          <el-button type="primary" @click="choosechannel">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// const dayjs = require('dayjs')
import { getTime } from '@/utils/getTimer.js'
import { orderState, orderList, repDetail, repVal, createOrder, cancelOrder, getInner, channelApi } from '@/api'
export default {
  data() {
    return {
      tablekey: false,
      // 校验规则
      creatFormRules: {
        innerCode: [{ required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 10, message: '在1-10个字符之间', trigger: 'blur' }
        ],
        productType: [{ required: true, message: '请选择', trigger: 'blur' }],
        assignorId: [{ required: true, message: '请选择', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 40, message: '在1-40个字符之间', trigger: 'blur' }
        ]
      },
      goodsDialog: false,
      channelList: [],
      // 新增工单
      creatForm: {
        createType: 1,
        innerCode: '',
        productType: '',
        userId: '',
        assignorId: '请选择',
        desc: '',
        details: []
      },
      // 工单列表信息
      workOrderInfo: {
        taskCode: '',
        status: ''
      },
      innerList: [], // 运营人员列表
      desc: '',
      stateList: [], // 工单状态列表
      orderLists: [], // 工单列表
      pageIndex: 0,
      pageSize: 10,
      totalCount: 0, // 总数
      totalPage: 0, // 总页数
      detailsVisible: false, // 控制查看详情dialog的显示隐藏
      loading: true, // 页面进入加载中
      // 工单方式
      typeMap: {
        0: '自动',
        1: '手动'
      },
      detailList: {}, // 详情列表
      titleImg: '',
      titleImg1: '',
      taskId: '',
      repDialog: false, // 控制补货详情dialog的显示隐藏
      repList: [], // 补货列表
      againDialog: false,
      addOrderList: [], // 新增工单
      orderAlert: {
        alertValue: 10
      }, // 预警值
      alertDialog: false,
      task: {
        taskName: '',
        taskIds: ''
      }
    }
  },
  created() {
    // 获取工单状态
    this.getOrderState()
    // 获取工单列表
    this.getOrderList({ pageIndex: this.pageIndex, pageSize: 10, isRepair:
      false
    })
  },
  methods: {
    // 新建提交
    submitCreate() {
      this.$refs.creatFormRef.validate(async(valid) => {
        if (!valid) return
        this.creatForm.assignorId = this.creatForm.userId
        this.creatForm.userId = 1
        // console.log(this.creatForm)
        try {
          const res = await createOrder(this.creatForm)
          if (res.data) {
            this.$message({
              message: '添加成功！',
              type: 'success'
            })
            this.creatForm = {
              createType: 1,
              innerCode: '',
              productType: '',
              userId: '',
              assignorId: '请选择',
              desc: '',
              details: []
            }
          }
          setTimeout(() => {
            this.againDialog = false
          }, 0)
        } catch (err) {
          return this.$message.error(err.response.data)
        }
      })
    },
    // 选择添加的清单选项
    choosechannel() {
      const arr = this.channelList.filter(item => item.render !== '-')
      arr.forEach(item => {
        this.creatForm.details.push({
          channelCode: item.channelCode,
          expectCapacity: item.addNum,
          skuId: item.skuId,
          skuName: item.sku.skuName,
          skuImage: item.sku.skuImage
        })
      })
      this.goodsDialog = false
    },
    // 改变弹窗数据
    changeDia(arr) {
      arr.forEach(item => {
        if (!item.sku) {
          item.sku = {}
          item.sku.brandName = '-'
          item.currentCapacity = '-'
          item.render = '-'
          item.max = '货道暂时无商品'
        } else {
          item.render = item.maxCapacity - item.currentCapacity
          item.addNum = item.maxCapacity - item.currentCapacity
          item.max = item.maxCapacity - item.currentCapacity
        }
      })
    },
    // inputNum 在 table中只能加一次，可以通过设置 tablekey 属性 true 或 false
    handleChange() {
      this.tablekey = !this.tablekey
    },
    // 点开补货清单的回调
    async openGoodsDialog() {
      if (this.creatForm.innerCode === '') {
        this.$message.info('请输入设备编号')
        return
      }
      const res = await channelApi(this.creatForm.innerCode)
      this.channelList = res.data
      // console.log(this.channelList)
      this.changeDia(this.channelList)
      this.goodsDialog = true
    },
    // 输入框失焦事件
    async innerCodeBlur() {
      // 获取运营人员列表
      const res = await getInner(this.creatForm.innerCode)
      this.innerList = res.data
    },
    // 点击打开补货预警值dialog
    showalertDIalog() {
      this.alertDialog = true
      this.getrepVal()
    },
    // 获取补货预警值
    async getrepVal() {
      const res = await repVal()
      // console.log(res)
      this.alertValue = res.data
    },
    // 获取工单状态
    async getOrderState() {
      const res = await orderState()
      this.stateList = res.data
      // console.log(this.stateList)
    },
    // 时间转换方法
    // getTime(val) {
    //   return dayjs(val, 'YYYY.MM.DD hh:mm:ss').format('YYYY.MM.DD hh:mm:ss')
    // },
    // 获取工单列表
    async getOrderList(obj) {
      const res = await orderList(obj)
      // console.log(obj)
      // console.log(res)
      // this.typeList = res.data.currentPageRecords
      // console.log(this.typeList)
      this.orderLists = res.data.currentPageRecords
      // 时间转换
      this.orderLists.forEach(item => {
        item.createTime = getTime(item.createTime)
      })
      this.pageIndex = Number(res.data.pageIndex)
      this.pageSize = res.data.pageSize
      this.totalCount = res.data.totalCount
      this.totalPage = Number(res.data.totalPage)
      // 请求完结束加载中
      this.loading = false
      // this.taskCode = this.workOrderInfo.taskCode
      // this.status = this.workOrderInfo.status
    },
    // 翻页
    dowmFn(val) {
      this.getOrderList({ pageIndex: this.pageIndex + val, pageSize: 10, isRepair:
        false
      })
    },
    // 点击查询
    onSubmit() {
      this.getOrderList({ status: this.workOrderInfo.status, taskCode: this.workOrderInfo.taskCode })
    },
    // 点击打开查看详情
    handleClick(val) {
      console.log(val)
      this.detailList = val
      this.detailsVisible = true
      this.detailList.taskStatusTypeEntity = this.detailList.taskStatusTypeEntity.statusName
      this.task.taskIds = this.detailList.taskType.taskId
      this.task.taskName = this.detailList.taskType.taskName
      this.detailList.taskType = this.detailList.taskType.typeName
      this.taskId = this.detailList.taskId
      this.desc = this.detailList.desc
      // console.log(this.taskId)
      if (val.taskStatusTypeEntity === '取消') {
        this.titleImg = require('@/assets/common/qx.png')
        this.titleImg1 = require('@/assets/common/qx1.png')
      } else if (val.taskStatusTypeEntity === '待办') {
        this.titleImg = require('@/assets/common/daiban.png')
        this.titleImg1 = require('@/assets/common/daiban1.png')
      } else if (val.taskStatusTypeEntity === '完成') {
        this.titleImg = require('@/assets/common/done.png')
        this.titleImg1 = require('@/assets/common/done1.png')
      }
    },
    // 点击关闭查看详情
    closedetailsVisible() {
      this.detailsVisible = false
    },
    // 点击查看补货详情
    async repDetail() {
      const { data: res } = await repDetail(this.detailList)
      // console.log(res)
      this.repList = res
      this.repDialog = true
    },
    // 关闭补货详情
    closeRepDialog() {
      this.repDialog = false
    },
    // 点击打开重新创建||取消工单
    async showDialog() {
      if (this.detailList.taskStatusTypeEntity === '待办') {
        this.$confirm('取消工单后，将不能恢复，是否确认取消？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await cancelOrder({ taskId: this.taskId, desc: this.desc })
          this.getOrderList()
          this.againDialog = false
          this.closedetailsVisible()
        })
      } else {
        // console.log(this.detailList)
        this.creatForm.innerCode = this.detailList.innerCode
        this.creatForm.productType = this.detailList.productType
        this.creatForm.userId = this.detailList.userId
        this.creatForm.desc = this.detailList.desc
        this.creatForm.assignorId = this.detailList.userName
        this.creatForm.productType = this.detailList.taskType
        const res = await getInner(this.creatForm.innerCode)
        this.innerList = res.data
        this.againDialog = true
      }
    },
    // 关闭新增工单的显示隐藏
    closeAgainDialog() {
      this.againDialog = false
      this.$refs.creatFormRef.resetFields()
      this.creatForm = {
        createType: 1,
        innerCode: '',
        productType: '',
        userId: '',
        assignorId: '请选择',
        desc: '',
        details: []
      }
    },
    // 点击新增工单
    showCreateOrder() {
      this.againDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
  .box-card {
    margin: 20px;
    padding: 5px;
  }
  label {
    font-size: 20px !important;
  }
  // 分页器
  // .el-pagination{
  //   height: 40px;
  //   font-size: 16px;
  //   // display: flex;
  //   // justify-content: space-between;
  //   // align-items: center;
  //   // line-height: 60px;
  //   // vertical-align: middle;
  //   margin-top: 20px;
  // }
  .btns {
    float: right;
  }
  // .left {
  //   color:#e5e2e5;
  // }
  // .btn {
  //   background-color: #d5ddf8;
  //   margin-right: 8px;
  // }
  // .dialog{
  //   background-color: #fff;
  // }
  // ::v-deep .el-input__inner{
  //   border:none;
  // }
  ::v-deep.el-dialog{
    border-radius: 5px;
  }
  .detailBtn{
    padding-left: 15px;
    color: #5f84ff;
  }
  .titleImg{
    background-color: #f8f8f8;
    width: 590px;
    height:54px;
    display:flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
  }
  .titleImgLeft:nth-child(1) {
    padding: 30px 20px;
    font-size: 14px;
    display: flex;
    align-items: center;
    img{
      margin-right: 10px;
    }
  }
  .titleImgRight:nth-child(1){
    margin-right: 76px;
    margin-bottom: 7px;
  }
  .el-dialog__body{
    height: 500px;
  }
</style>
